/**
 * 226. 翻转二叉树
 * https://leetcode-cn.com/problems/invert-binary-tree/
 */
public class Solutions_226 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.right = new TreeNode(7);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(9);  // output: {4,7,2,9,6,3,1}

        TreeNode result = invertTree(root);
        System.out.println(result);
    }

    /**
     * 前序遍历（根左右）完成二叉树的翻转
     * @param root
     * @return
     */
    public static TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        if (root.left == null && root.right == null) {
            return root;
        }
        // 对于每一个父节点，都进行左右子树翻转的操作，最终实现整个树的翻转
        TreeNode tempNode = root.left;
        // 翻转实现：递归进入右子树，返回的结果作为左子树
        root.left = invertTree(root.right);
        root.right = invertTree(tempNode);
        return root;
    }
}
